package com.lib.common.dialog_fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.lib.common.R;
import com.google.android.material.textfield.TextInputEditText;
import com.lib.utils.RegexUtils;

import java.lang.ref.WeakReference;

@SuppressLint("ValidFragment")
public class LoginDialogFragment extends BaseDialogFragment implements View.OnClickListener {
    private FragmentActivity mActivity;

    private TextInputEditText mAccount;
    private TextInputEditText mPwd;
    private View mBtn;

    public LoginDialogFragment() {
    }

    @Override
    @SuppressLint("InflateParams")
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setCancelable(false);

        mActivity = new WeakReference<>(getActivity()).get();
        mView = LayoutInflater.from(mActivity).inflate(R.layout.dialog_fragment_login, null);

        mAccount = mView.findViewById(R.id.account);
        mPwd = mView.findViewById(R.id.pwd);

        mBtn = mView.findViewById(R.id.login);
        mBtn.setOnClickListener(this);
        mView.findViewById(R.id.toReg).setOnClickListener(this);
        mView.findViewById(R.id.toFindPwd).setOnClickListener(this);

        String str = mActivity.getSharedPreferences("ctmd", Context.MODE_PRIVATE).getString("l_a", null);
        if (str != null) {
            mAccount.setText(str);
        }
    }

    @Override
    public void onClick(final View v) {
        int i = v.getId();
        if (i == R.id.login) {
            Editable userName = mAccount.getText();
            final String userNameStr;
            if (userName == null || TextUtils.isEmpty(userNameStr = userName.toString()) || !RegexUtils.isMobileExact(userNameStr)) {
                Toast.makeText(mActivity, getString(R.string.please_check_phone), Toast.LENGTH_SHORT).show();
                return;
            }
            Editable pwd = mPwd.getText();
            String pwdStr;
            if (pwd == null || TextUtils.isEmpty(pwdStr = pwd.toString())) {
                Toast.makeText(mActivity, getString(R.string.no_standard_pwd), Toast.LENGTH_SHORT).show();
                return;
            }
            mBtn.setEnabled(false);
            new LoginSuccessDialogFragment().show(mActivity);
        } else if (i == R.id.toReg) {
            new RegDialogFragment().show(mActivity);
        } else if (i == R.id.toFindPwd) {
            new FindPwdDialogFragment().show(mActivity);
        }
    }
}